import { createI18n } from 'vue-i18n';
import type { I18nOptions } from 'vue-i18n';
import zhLocale from './zh';
import enLocale from './en';
import engbLocale from './en-GB';
import { zhCN, dateZhCN, enUS, dateEnUS, enGB, dateEnGB } from './naiveUiLang';
import { dateFormatZh, dateFormatOther } from './dateFormat';

type Lang = keyof typeof sourceMessage;

const sourceMessage = {
	en: {
		...enLocale,
	},
	zh: {
		...zhLocale,
	},
	'en-GB': {
		...engbLocale,
	},
};

const messages: I18nOptions['messages'] = sourceMessage;

/** i18n时间格式国际化 (不使用此方法) */
const datetimeFormats = {
	// 'en-US': dateFormat,
	zh: dateFormatZh,
	en: dateFormatOther,
	'en-GB': dateFormatOther,
};

/** naive-ui国际化 */
const naiveLocale = {
	en: {
		locale: enUS,
		dateLocale: dateEnUS,
	},
	zh: {
		locale: zhCN,
		dateLocale: dateZhCN,
	},
	'en-GB': {
		locale: enGB,
		dateLocale: dateEnGB,
	},
};

export function getNaiveLanguage(): { locale: any; dateLocale: any } {
	const lang = localStorage.getItem('language');
	return naiveLocale[lang || 'zh'];
}

export function setLanguage(lang: Lang) {
	i18n.global.locale.value = lang;
	localStorage.setItem('language', unref(lang));
	location.reload();
}

export function getLanguage() {
	const chooseLanguage = localStorage.getItem('language');
	if (chooseLanguage) return chooseLanguage;

	const language = (navigator.language || navigator['browserLanguage']).toLowerCase();
	const locales = Object.keys(messages!);
	for (const locale of locales) {
		if (language.indexOf(locale) > -1) {
			return locale;
		}
	}
	return 'zh';
}

const i18n = createI18n({
	legacy: false,
	locale: getLanguage(),
	messages,
	// datetimeFormats,
});

export default i18n;
